#!/usr/bin/python

##===============================================================================
# 
# flickr.py
#    Copyright 2004-2006 James Clarke <james@jamesclarke.info>
#    Portions Copyright 2007-2008 Joshua Henderson <joshhendo@gmail.com>
# flickr_tray.py
#    Copyright 2008 Michael Kania <mkania@umail.ucsb.edu>
#
#
# Icon Design:
#  AODdesign! Flickr Orbs Logo Icons
#  http://www.aoddesign.com/
# 
# THIS SOFTWARE IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, AND MAY BE
# COPIED, MODIFIED OR DISTRIBUTED IN ANY WAY, AS LONG AS THIS NOTICE
# AND ACKNOWLEDGEMENT OF AUTHORSHIP REMAIN.
# 
# 03-07-2008
#    Initial Version(0.1.0)
#===============================================================================

__author__ = "Michael Kania <mkania@umail.ucsb.edu>"
__version__ = ".0.1.0"
__copyright__ = "Copyright: 2008 Michael Kania"

import sys,os,commands
import gtk
import pynotify
import Image
import flickr
import random
import urllib 
import threading, gobject
from threading import Thread


class trayIcon(threading.Thread):
    
    
    def __init__(self, debug = False):
        threading.Thread.__init__(self)
       
        self.tray_icon = gtk.StatusIcon()
        if(debug):
            print "Create New Tray Icon"
            self.debug = True
            
        else:
            self.debug = False
        #self.tray_icon = gtk.status_icon_new_from_file("/home/mkania/workspace/FlickrWall/src/FlickrWall/img/flickr_orbs_plain_tray.png")
        self.tray_icon = gtk.status_icon_new_from_file("/usr/share/FlickrWall/flickr_orbs_plain_tray.png")
        self.tray_icon.set_tooltip("FlickrWall")
        self.tray_note = trayNotify(self,self.debug)
        
        self.tray_menu = gtk.Menu()
        next_menu_item = gtk.MenuItem("Get New Image", True)
        next_menu_item.connect('activate', self.next_image)
        
        #next_fav_item = gtk.MenuItem("Get Favorite",True)
        #next_fav_item.connect('activate',self.next_fav_image)
        
        chg_theme_item = gtk.MenuItem("Change Theme")
        chg_theme_item.connect('activate',self.chg_theme)
        
        quit_menu_item = gtk.MenuItem("Quit", True)
        quit_menu_item.connect('activate', self.quit)
        
        self.tray_menu.add(next_menu_item)
        #self.tray_menu.add(next_fav_item)
        self.tray_menu.add(chg_theme_item)
        self.tray_menu.add(quit_menu_item)
        
        self.tray_icon.connect('popup-menu', self.popup)
        
       
        self.run()
        

    def run(self):
        gtk.main()

    
            
    def next_image(self, widget):
        if(self.debug):
            print "\tnext!"
        self.thread_flickrwall = Thread(target=flickrWall, args=(self.tray_icon,self.tray_note,self.debug,)).start()

    
    def next_fav_image(self,widget):
        if(self.debug):
            print "\tnext favorite!"
        self.thread_flickrwall = Thread(target=flickrWall, args=(self.tray_icon,self.tray_note,self.debug,)).start()

    def chg_theme(self,widget):
        if(self.debug):
            print "\tchange theme!"

            
    def get_geometry(self):
            icon_screen,icon_rectangle,icon_orient = self.tray_icon.get_geometry()
            self.icon_x = icon_rectangle.x
            self.icon_y = icon_rectangle.y
            self.icon_width = icon_rectangle.width
            self.icon_height = icon_rectangle.height
            if(self.debug):
                print (self.icon_x,self.icon_y)
                print (self.icon_width,self.icon_height)
            return (self.icon_x,self.icon_y,self.icon_width,self.icon_height)
                
    def quit(self, widget):
        if(self.debug):
            print "\tExit Application"
        urllib.urlcleanup()
        del self
        gtk.main_quit() 
        print "FlickrWall done"
        sys.exit()
        
        
    def popup(self, widget, button, time):
        if(self.debug):
             print "\tButton %i pressed" %button 
        if button == 3:
            if self.tray_menu:
                self.tray_menu.show_all()
                self.tray_menu.popup(None, None, gtk.status_icon_position_menu,
                      button, time, widget)
                 
    def update_tooltip(status):
        #python has no switch?!
        if(status == "retrieve"):
            self.tray_icon.set_tooltip("Retrieving Wallpaper")
            self.tray_icon = gtk.set_from_file("/usr/share/FlickrWall/flickr_orbs.png")
        elif(status == "idle"):
            self.tray_icon.set_tooltip("FlickrWall")
       
    def getTrayIcon(self):
        return self.tray_icon
    
    def getTrayNote(self):
        return self.tray_note
        
class flickrWall(threading.Thread):
    def __init__(self,tray_icon, tray_note,debug = False):
        threading.Thread.__init__(self)
        if(debug):
            print "Create New FlickrWall"
            self.debug = True
        else:
            self.debug = False
        self.tray_icon = tray_icon
        self.tray_note = tray_note
        self.tray_icon.set_blinking(True)
        self.get_photo_url("66885150@N00", "Original", 50, False)
        self.set_wallpaper()
        self.tray_icon.set_blinking(False)
    
    def download_status(self,count,blockSize,totalSize):
        percentage = ( (float(count*blockSize) /totalSize)*100)
        if(percentage < 100):
            self.tray_icon.set_tooltip("Downloading: %.0f %%" %percentage)
        else:
            self.tray_icon.set_tooltip("FlickrWall")
        
        
    
    def load_photo(self):
        self.url = self.photo.getURL(size='Original', urlType='source')
                    
        if(self.debug):
            print "\tload_photo"
            print "\t\tRetrieving url: %s" %self.url
        
        file, mime = urllib.urlretrieve(url = self.url ,reporthook=self.download_status)
        
        if(self.debug):
            print file
            print mime
        self.wallpaper = Image.open(file)
        
        print self.wallpaper.size
        self.wallpaper = self.wallpaper.resize((1280,800),Image.ANTIALIAS)
        
        self.wallpaper.save(os.path.expanduser("~") + "/Wallpaper.png","PNG")
        commands.getoutput("gconftool -s /desktop/gnome/background/picture_filename -t string ~/Wallpaper.png")

        urllib.urlcleanup()
        

    
        
    
    def get_photo_url(self, groupid, size, number, equal=False):
        if(self.debug):
            print "\tget_photo_url"
            print "\t\tGroupID: %s, " %groupid + "Size: %s, " %size + "Number: %i" %number
        group = flickr.Group(groupid)
        self.photos = group.getPhotos(per_page=number)
    
        

    def check_size(self):
        if (self.debug):
            print "\tcheck_size"
        
        rand = random.randint(0, (len(self.photos)-1))
        if(self.debug):
            print "\t\tRandom: %i" %rand
            print "\t\tPhotos Length: %i" %len(self.photos)
        self.photo = self.photos[rand]
        self.sizes = self.photo.getSizes()
        if(self.debug):
            print "\t\tDict length:%i" %len(self.sizes)
        if(len(self.sizes) > 5):
            self.size = self.sizes[5]
            self.width = self.size["width"]
            self.height = self.size["height"]
               
            if (self.height > self.width):
                print "Bad Orientation"
                del self.photos[rand]
                    
            elif (self.width < 1024):
                print "Too Small"
                del self.photos[rand]
            else:
                if(self.debug):
                    print "\t\t No URL"
                return self.photo 
        else:
            return None
        
        
    def set_wallpaper(self):
        if(self.debug):
            print "\tset_wallpaper"
                
        while (True):
            self.tray_icon.set_tooltip("Looking for the perfect picture")
            self.photo = self.check_size()
            if(self.photo != None):
                try:
                    self.load_photo()
                    self.tray_note.notify("FlickrWall","Wallpaper has been set")
                    break;
                except flickr.FlickrError, e:
                    print "Error Loading Photo"    

   
    
class trayNotify(threading.Thread):
    def __init__(self,tray_icon,debug = False):
        threading.Thread.__init__(self)
        self.icon_x,self.icon_y,self.icon_width,self.icon_height = tray_icon.get_geometry()
       
    def notify(self,title,text):
        if not pynotify.init(title):
            sys.exit(1)
            
#        uri = "/home/mkania/Wallpaper.png"
#
        self.note = pynotify.Notification( title,text)    
 
        self.note.set_hint("x", self.icon_x + (self.icon_width/2))
        self.note.set_hint("y", self.icon_y + (self.icon_height/2))
        self.note.set_timeout(1750) # 1.5 seconds

#        # Image URI

        if not self.note.show():
            print "Failed to send notification"
            sys.exit(1)

              
if __name__ == "__main__":

    gtk.gdk.threads_init()
    debug = True
    print "Running FlickrWall"
    trayIcon(debug).start_()
    